package com.example.myapplication.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.myapplication.tools.NfcVUtil;
import com.example.myapplication.R;
import com.example.myapplication.tools.RFIDWriteReadUtile;
import com.example.myapplication.tools.StringUtils;
import com.example.myapplication.tools.ToastUtils;

public class NfcExample extends Activity {
 
	NfcAdapter adapter;
	PendingIntent pendingIntent;
	IntentFilter writeTagFilters[];
	Tag mytag;
	Context ctx;
	AlertDialog mDialog;
	NfcVUtil util;
	NfcV nfcV;
	EditText etIdinput;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nfc_detail);
		ctx = this;
		etIdinput = findViewById(R.id.et_id);
        adapter = NfcAdapter.getDefaultAdapter(this);
		pendingIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

		IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
		tagDetected.addCategory(Intent.CATEGORY_DEFAULT);

		writeTagFilters = new IntentFilter[] { tagDetected };
		
		// Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.dialog_text).setTitle(R.string.nfc_card_waiting);
		mDialog = builder.create();
		mDialog.show();
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		resolveIntent(intent);
	}

	void resolveIntent(Intent intent) {

		Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//		intent.getParcelableExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		if (tag != null) {
			processTag(intent);
		}
	}

	//结果大写
	private String ByteArrayToHexString(byte[] inarray) {
		int i, j, in;
		String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
				"B", "C", "D", "E", "F" };
		String out = "";
//		for (j = 0; j < inarray.length; ++j) {
//			in = (int) inarray[j] & 0xff;
//			i = (in >> 4) & 0x0f;
//			out += hex[i];
//			i = in & 0x0f;
//			out += hex[i];
//		}
		for (j = inarray.length - 1; j >= 0 ; j--) {
			in = (int) inarray[j] & 0xff;
			i = (in >> 4) & 0x0f;
			out += hex[i];
			i = in & 0x0f;
			out += hex[i];
		}
		return out;
	}

	private String flipHexStr(String s){
		StringBuilder  result = new StringBuilder();
		for (int i = s.length()-2; i >= 0; i=i-2) {
			result.append(new StringBuilder(s.substring(i,i+2)));
		}
		return result.toString();
	}


	public void processTag(Intent intent) {//处理tag
		//获取到卡对象
		Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		String[] arr = tag.getTechList();
		if(arr.length > 0 && arr[0].contains("android.nfc.tech.NfcV")){
//获取卡id这里即uid
			byte[] aa = tag.getId();
			String UID = ByteArrayToHexString(aa);//
//		String UID = flipHexStr(str);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("RFID已经连接，可以开始读写\n UID:" + UID).setTitle("提示");
			mDialog = builder.create();
			mDialog.show();
			try {
				nfcV = NfcV.get(tag);
				if(nfcV != null) {
					nfcV.connect();//建立连接
					util = new NfcVUtil(nfcV);//创建工具类，操作连接
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			ToastUtils.showMessages("卡格式不正确",ctx);
		}


	}

	@Override
	protected void onPause() {
		super.onPause();
		if (adapter != null)
			//设置程序不优先处理
			adapter.disableForegroundDispatch(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (adapter != null)
			//设置程序优先处理
			adapter.enableForegroundDispatch(this, pendingIntent,
					writeTagFilters, null);
	}

	/**
	 * 写入RFID卡数据，第0块的第七位[6]显示真实数据从第一块开始到第几块结束，
	 *
	 * 第0块的第八位[7]显示最后一块保存的长度
	 * @param v
	 */
	public void write(View v){
		if(!isEnable()){
			return;
		}

		try {
			String info = etIdinput.getText().toString();

//			String ss = StringUtils.stringToHexString(info);//真实数据先转化为16进制字符。例如1234qwer转化位16长度
//			if(ss.length() > 8){
//				int time = ss.length()/8;
//				int end = ss.length()%8;
//				List<String> list = new ArrayList<>();//31323361  62637177
//				for(int i = 0 ; i < time;i++){
//					list.add(ss.substring(i*8,8+i*8));
//				}
//				if(end != 0){
//					list.add(ss.substring(time*8));
//				}
//				for(int j = 0 ; j < list.size() ;j ++){
//					String infs = list.get(j);
//					int dLength = 8 - infs.length();
//					for(int i =0 ; i < dLength ; i++){
//						infs = infs + "0";
//					}
//					byte[] sss = util.hexStringToBytes(infs);
//					util.writeBlock(j+1,sss);//分多次保存长数据
//				}
//				util.writeBlock(0,util.hexStringToBytes("000000" + (time+1) + end));//保存格式信息
//			}else{
//				String ss2 = StringUtils.stringToHexString(info);//真实数据先转化为16进制字符。例如1234qwer转化位16长度
//				int dLength = 8 - ss2.length();
//				for(int i =0 ; i < dLength ; i++){
//					ss2 = ss2 + "0";
//				}
//				byte[] sss = util.hexStringToBytes(ss2);
//				util.writeBlock(0,util.hexStringToBytes("00000010"));//保存格式信息
//				boolean isSuccess = util.writeBlock(1,sss);//单次保存
//				ToastUtils.showMessages("写入数据" + info + " "+(isSuccess?"成功":"失败") ,ctx);
//			}


			ArrayList<String> block_dataList = new ArrayList<>();
			String temp = RFIDWriteReadUtile.getWriteRfidDataByStr(info);
			getRFIDData(temp,block_dataList);
			for(int i = 0 ; i < block_dataList.size() ; i ++){
				String writeStr = (block_dataList.get(i));
				util.writeBlock(i,util.hexStringToBytes(writeStr));
			}
		} catch (IOException e) {
			System.out.println("=======>  exception ");
			e.printStackTrace();
		}
	}

	/**
	 * 获取写入的barcode字符串   每条list不够8为按F补齐
	 * @param str
	 * @param list
	 */
	public void getRFIDData(String str , ArrayList<String> list){
		if(list == null){
			list = new ArrayList<>();
		}else{
			list.clear();
		}
		str = str.toUpperCase();
		if(str.length() > 8){
			int _blocks = str.length() / 8;
			int end = str.length() % 8;
			for(int i = 0 ; i < _blocks ; i ++){
				int start = i*8;
				String tempStr = str.substring(start,start + 8);
				list.add(tempStr);
			}
			if(end > 0){
				String tempStr = str.substring(_blocks * 8);
				for(int i = 0;i < 8-end ; i ++){
					tempStr += "F";
				}
				list.add(tempStr);
			}
		}else if(str.length() == 8){
			list.add(str);
		}else{
			String tempStr = str;
			for(int i = 0;i < 8 - str.length() ; i ++){
				tempStr += "F";
			}
			list.add(tempStr);
		}
	}

	public void read(View v){
		if(!isEnable()){
			return;
		}
		try {
			String readOneBlockStr = "";
			for(int i = 0 ; i < 5; i ++){
				readOneBlockStr += util.readOneBlock(i);//读取block在1位置的内容
			}
			String result = RFIDWriteReadUtile.readRfidDataByHex(readOneBlockStr);
			ToastUtils.showMessages("读取结果 : " + result ,ctx);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setAFI(View v){
		if(!isEnable()){
			return;
		}
		byte b = 1;
		try {
			boolean succes = util.setAFIState(b);
			ToastUtils.showMessages("is Success : "+succes,ctx);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void getAFI(View v){
		if(!isEnable()){
			return;
		}
		String result = util.getAFI();
		ToastUtils.showMessages("result : "+result,ctx);
	}

	public void setDSFID(View v){
		if(!isEnable()){
			return;
		}
		byte b = 1;
		try {
			boolean succes = util.setDSFIDState(b);
			ToastUtils.showMessages("is Success : "+succes,ctx);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	Handler handler= new Handler(){
		@Override
		public void handleMessage(@NonNull Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case 1:
					ToastUtils.showMessages("请先连接RFID卡" ,ctx);
					break;
				case 2:
					ToastUtils.showMessages("接连中断，请重新连接" ,ctx);
					break;
			}
		}
	};

	private boolean isEnable(){
    	if(util == null){
    		handler.sendEmptyMessage(1);
    		return false;
		}
    	if(nfcV ==null){
			handler.sendEmptyMessage(1);
    		return false;
		}
    	if(!nfcV.isConnected()){
			handler.sendEmptyMessage(2);
    		return false;
		}
    	return true;
	}

}
